<template>
  <div class="search">
    <div class="search-title clearfix">
      <a href="javascript:;" class="goBack" @click.stop="goBack"></a>
      <input type="text" id="searchWord" class="searchWord" v-model="search.contractNo" @focus.stop="onFocus">
      <a href="javascript:;" class="ico-search" @click="searchList"></a>
    </div>
    <div class="list-container">
      <div class="msg">密码有效期自获取开始1个小时，不限次数开门</div>
      <div id="ico-loading-getLockPwd" v-if="lalala">
        <div class="rotate"></div>
      </div>
      <mt-loadmore
        :bottom-method="loadBottom"
        :bottom-all-loaded="allLoaded"
        :auto-fill="false"
        ref="loadmore">
        <ul id="deal-house-list">
          <li v-for="(house, index) in dealHouseList" class="clearfix">
            <div class="house-left" @click.stop="toServiceDiary(house)">
              <h5>{{house.contractNo}}<span v-if="house.endTime" class="count-down">有效期：{{house.endTime}}</span></h5>
              <p>{{house.houseAddress}}</p>
            </div>
            <div class="house-right">
              <button v-if='house.lockPwd'  @click="copyText(house)"><span :ref="house.contractNo">{{house.lockPwd}}</span><br/>复制密码</button>
              <button v-else  @click="getPassword(house,index)">查看密码</button>
            </div>
          </li>
        </ul>
      </mt-loadmore>
    </div>
    <mt-spinner
      type="snake"
      color="#ff5658"
      :size='20'
      :class="'loadingMore'"
      v-show="allLoaded"
    ></mt-spinner>
  </div>
</template>
<script>
  import { EMPLOYEE_KEY, SEARCH_HISTORY_CACHE_KEY, HOUSE_NUMBER_LSIT_PATH, GET_LOCK_TEMP_PASSWORD_PORT, USER_ID, deviceHeight, globalHostServiceDiary } from '../../assets/js/config'
  import cache from '../../assets/js/cache'
  let historyCache = cache.get(SEARCH_HISTORY_CACHE_KEY)
  historyCache = historyCache === null ? [] : historyCache.split(',')
  export default {
    name: 'passwordList',
    data () {
      return {
        deviceHeight,
        lalala: false,
        allLoaded: false,
        search: {
          contractNo: '',
          pageNum: 1,
          numPerPage: 20,
          token: ''
        },
        dealHouseList: [],
        searchHistoryCache: historyCache,
        showMatchList: 0,
        showSearchCasePanel: 0,
        showHistoryList: 0,
        dialogue: '正在获取密码，请稍后',
        switchOpen: [],
        getPasswordJson: {
          houseId: '',
          userId: '',
          token: ''
        }
      }
    },
    created () {
      this.getPasswordJson.token = this.search.token = cache.get(EMPLOYEE_KEY)
      this.getPasswordJson.userId = cache.get(USER_ID)
      let params = this.$route.params
      if (params.contractNo !== undefined && params.contractNo !== '') {
        this.search.contractNo = params.contractNo
      }
      this.getDealHouseList()
    },
    methods: {
      goBack () {
        this.$router.push({path: '/index'})
      },
      onFocus () {
        let contractNo = this.search.contractNo
        this.$router.push({name: 'serviceList', params: {contractNo, state: 1}})
      },
      searchList () {
        this.dealHouseList = []
        this.search.pageNum = 1
        this.getDealHouseList()
      },
      loadBottom () {
        this.getDealHouseList()
        this.$refs.loadmore.onBottomLoaded()
      },
      getDealHouseList () {
        this.allLoaded = true
        let myVue = this
        let getHouseListOption = {
          url: HOUSE_NUMBER_LSIT_PATH,
          sendData: myVue.search,
          success (data) {
            let dataList = data.record
            if (dataList.length < 20) {
              myVue.$toast({
                message: '没有更多数据了',
                duration: 1000
              })
            }
            dataList.map(function (ele, idx) {
              myVue.dealHouseList.push(ele)
            })
            myVue.search.pageNum++
            myVue.allLoaded = false
          }
        }
        this.post(getHouseListOption)
      },
      clearHistory () {
        cache.del(SEARCH_HISTORY_CACHE_KEY)
        this.searchHistoryCache = []
      },
      ensureMoreCases () {
        this.searchList()
      },
      toServiceDiary (house) {
        let isExistReport = house.isExistReport
        if (house.id && isExistReport && isExistReport === '1') {
          window.location.href = globalHostServiceDiary + '/index.html?houseId=' + house.id
        } else {
          let instance = this.$toast('服务日记正在紧张制作中...')
          setTimeout(() => {
            instance.close()
          }, 2000)
        }
      },
      getPassword (house, idx) {
        let myVue = this
        myVue.lalala = true
        this.$toast({
          message: this.dialogue,
          iconClass: 'icon icon-success',
          duration: 2000
        })
        this.getPasswordJson.houseId = house.id
        setTimeout(() => {
          this.post({
            url: GET_LOCK_TEMP_PASSWORD_PORT,
            sendData: this.getPasswordJson,
            success (data) {
                //        为数据扩充字段，为了指定添加密码
              myVue.dealHouseList[idx].lockPwd = data.password
              myVue.dealHouseList[idx].endTime = data.endTime
              myVue.lalala = false // 真实dom更改触动虚拟dom的刷新
            }
          })
        }, 2000)
      },
      copyText (house) { // 复制文字
        let contractNo = house.contractNo
        let selection = window.getSelection()
        let range = document.createRange()
        range.selectNodeContents(this.$refs[contractNo][0])
        selection.removeAllRanges()
        selection.addRange(range)
        let result = document.execCommand('Copy', false, null)
        if (result) {
          this.$toast({
            message: '复制成功',
            duration: 1500,
            iconClass: 'icon icon-success'
          })
        }
        return false
      }
    }
  }
</script>
<style scoped>
  @import '../../assets/css/searchStyle.css';
  @import '../../assets/css/serviceListStyle.css';
  @keyframes rotating {
    0% {
      -webkit-transform: rotate(0deg);
      -moz-transform: rotate(0deg);
      -ms-transform: rotate(0deg);
      -o-transform: rotate(0deg);
      transform: rotate(0deg);
    }
    100% {
      -webkit-transform: rotate(360deg);
      -moz-transform: rotate(360deg);
      -ms-transform: rotate(360deg);
      -o-transform: rotate(360deg);
      transform: rotate(360deg);
    }
  }
  #ico-loading-getLockPwd {
    position: fixed;
    top:50%;
    left:50%;
    -webkit-transform: translate(-50%,-50%);
    -moz-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    -o-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
    z-index:-9999;
  }
  #ico-loading-getLockPwd .rotate {
    width:16px;
    height: 16px;
    border:4px solid #ff5658;
    border-top:0 none;
    border-radius: 50%;
    -webkit-border-radius: 50%;
    -webkit-animation:rotating linear 0.5s;
    animation:rotating linear 0.5s;
  }
  .danger{
    background-color: #ff5658;
    color:#fff;
  }
  .msg{
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    height:.8rem;
    line-height:.8rem;
    z-index: 999;
    width:100%;
    background-color: #fff;
    text-align: left;
    padding:0 .2rem;
    color:#ff5658;
    font-size:.24rem;
    margin-bottom: 1px;
  }
  .count-down{
    float: right;
    padding-right:4%;
    font-size: .2rem;
  }
</style>

